/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package com.hundredhealth.rose.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.hundredhealth.rose.R;
import com.hundredhealth.rose.base.BaseFrameActivity;
import com.hundredhealth.rose.delegate.MainDelegate;
import com.hundredhealth.rose.model.HealthActivity;
import com.hundredhealth.rose.model.Vendor;
import com.hundredhealth.rose.service.GPSTracker;
import com.hundredhealth.rose.util.DistanceUtil;

public class MainActivity extends BaseFrameActivity<MainDelegate> implements View.OnClickListener {

    private static final String GPS_PERMISSION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String TAG = "MainActivity";
    private static final int REQUEST_CODE_PERMISSION = 1;

    @Override
    protected Class<MainDelegate> getDelegateClass() {
        return MainDelegate.class;
    }

    @Override
    protected void initToolbar() {

    }
    /**
     * 在这里写绑定事件监听相关方法
     */
    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        viewDelegate.get(R.id.historyActivityButton).setOnClickListener(this);
        viewDelegate.get(R.id.inputCustomer).setOnClickListener(this);
        viewDelegate.get(R.id.changeActivityButton).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.historyActivityButton:
                Intent historyIntent = new Intent(MainActivity.this, HistoryActivityListActivity.class);
                startActivity(historyIntent);
                break;
            case R.id.inputCustomer:
                Intent inputIntent = new Intent(MainActivity.this, CustomerInputActivity.class);
                startActivity(inputIntent);
                break;
            case R.id.changeActivityButton:
                Intent serverIntent = new Intent(MainActivity.this, CurrentActivityListActivity.class);
                startActivity(serverIntent);
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        autoGetActivityLocation();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    protected synchronized void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver, new IntentFilter(GPSTracker.str_receiver));
    }

    @Override
    protected synchronized void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
        Log.d(TAG, "- ON PAUSE -");
    }


    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        viewDelegate.stopGPSService();
        super.onDestroy();
        Log.d(TAG, "--- ON DESTROY ---");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    viewDelegate.startGPSService();
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "ACCESS_FINE_LOCATION Denied", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void autoGetActivityLocation() {
        try {
            if (ActivityCompat.checkSelfPermission(this, GPS_PERMISSION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{GPS_PERMISSION}, REQUEST_CODE_PERMISSION);
                return;
            }
            viewDelegate.startGPSService();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            double latitude = Double.valueOf(intent.getStringExtra("latutide"));
            double longitude = Double.valueOf(intent.getStringExtra("longitude"));

            // \n is for new line
            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "
                    + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
            Intent mIntent = MainActivity.this.getIntent();
            if (mIntent != null) {
                Vendor vendor = (Vendor) mIntent.getSerializableExtra(LoginActivity.KEY_VENDER);
                if (vendor != null) {
                    HealthActivity healthActivity1 = vendor.getHealthActivityList().get(0);
                    double distance1 = DistanceUtil.getDistance(longitude, latitude, healthActivity1.getLongitude(), healthActivity1.getLatutide());
                    HealthActivity healthActivity2 = vendor.getHealthActivityList().get(1);
                    double distance2 = DistanceUtil.getDistance(longitude, latitude, healthActivity2.getLongitude(), healthActivity2.getLatutide());
                    if (distance1 > distance2) {
                        viewDelegate.updateActivityInfo(healthActivity2.getDate(), vendor.getName(), healthActivity2.getLocation());
                    } else {
                        viewDelegate.updateActivityInfo(healthActivity1.getDate(), vendor.getName(), healthActivity1.getLocation());
                    }
                }
            }
        }
    };
}
